package com.javaketang.dky.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.javaketang.dky.entity.*;
import com.javaketang.dky.mapper.*;
import org.omg.CORBA.INTERNAL;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.text.DecimalFormat;
import java.util.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author dky
 * @since 2021-07-06
 */
@Controller
@RequestMapping("address")
public class EasybuyUserAddressController {

    //地址对象
    @Resource
    private EasybuyUserAddressMapper addressMapper;

    //购物车
    @Resource
    private ShoppingCarMapper carMapper;

    //商品类
    @Resource
    private EasybuyProductCategoryMapper categoryMapper;

    //订单类
    @Resource
    private EasybuyOrderMapper orderMapper;

    //订单详情类
    @Resource
    private EasybuyOrderDetailMapper detailMapper;

    //新闻类
    @Resource
    private EasybuyNewsMapper newsMapper;


    @RequestMapping("/addAddress")
    @ResponseBody
    public Map<String, Object> addAddress(Integer addressId, EasybuyUserAddress address, HttpSession session, Model model) {

        //创建map集合
        Map<String, Object> map = new HashMap<>();

        //获取session
        EasybuyUser user = (EasybuyUser) session.getAttribute("userSession");

        //查询购物车
        List<ShoppingCar> order = carMapper.selectList(new QueryWrapper<ShoppingCar>().eq("userId", user == null ? 0 : user.getId()).eq("isDelete", 0));


        //获取地址
        String addressss = address.getAddress();

        //总价格
        double sumPrice = 0;

        //商品id
        List<Integer> list = new ArrayList<>();

        //消费金额
        List<Double> lists = new ArrayList<>();

        //循环订单
        for (ShoppingCar news : order) {

            //累加
            sumPrice += news.getSumPrice();

            //赋值商品id
            list.add(news.getProductId());

            //赋值消费金额
            lists.add(news.getSumPrice());
        }


        //赋值总价格
        session.setAttribute("sumPriceCar", sumPrice);

        System.out.println("地址对象：" + address + "\t" + addressId);

        //订单号
        String replaceUUID = UUID.randomUUID().toString().replace("-", "");


        //添加
        if (addressId != null && addressId == -1) {
            address.setUserId(user.getId());
            address.setCreateTime(new Date());

            //添加地址
            int row = addressMapper.insert(address);

            //判断添加地址成功
            if (row > 0) {

                //购物车对象
                ShoppingCar car = new ShoppingCar();
                car.setIsDelete(1);

                //清空购物车
                int carRow = carMapper.update(car, new QueryWrapper<ShoppingCar>().eq("userId", user.getId()));

                //判断购物车是否清空
                if (carRow > 0) {

                    //订单类
                    EasybuyOrder order1 = new EasybuyOrder();
                    order1.setUserId(user.getId());  //赋值用户id
                    order1.setLoginName(user.getLoginName());//赋值登陆名
                    order1.setUserAddress(addressss);  //赋值地址
                    order1.setCost((float) sumPrice);  //赋值总价格
                    order1.setSerialNumber(replaceUUID);  //赋值订单号
                    order1.setCreateTime(new Date());
                    order1.setStatus(1);   //赋值订单是否确认

                    //添加订单类
                    int orderRow = orderMapper.insert(order1);

                    //获取订单id
                    int orderId = order1.getId();

                    System.out.println("订单id:" + orderId);

                    //判断订单添加成功
                    if (orderRow > 0) {


                        for (int i = 0; i < list.size(); i++) {

                            //创建订单详情类
                            EasybuyOrderDetail detail = new EasybuyOrderDetail();
                            detail.setOrderId(orderId);//赋值订单主键
                            detail.setProductId(list.get(i));
                            detail.setQuantity(order.get(i).getNumber());
                            detail.setCost(lists.get(i));

                            //添加订单详情类
                            int rowsDelail = detailMapper.insert(detail);

                            //判断订单详情
                            if (rowsDelail > 0) {

                                //查询订单号
                                EasybuyOrder easybuyOrder = orderMapper.selectById(orderId);

                                //赋值订单号
                                session.setAttribute("orderMark", easybuyOrder.getSerialNumber());
                                //赋值地址
                                session.setAttribute("address", easybuyOrder.getUserAddress());
                                map.put("status", 1);
                                map.put("message", "提交成功");
                            } else {
                                map.put("status", 0);
                                map.put("message", "订单第" + i + "此详情添加失败");
                            }

                        }

                    } else {

                        map.put("status", 0);
                        map.put("message", "订单添加失败！");

                    }


                } else {

                    map.put("status", 0);
                    map.put("message", "订单提交失败，地址提交未成功！");
                }

            } else {

                map.put("status", 0);
                map.put("message", "订单提交失败，地址提交未成功！");
            }

        } else {

            //查询地址
            EasybuyUserAddress easybuyUserAddress = addressMapper.selectById(addressId);

            //购物车对象
            ShoppingCar car = new ShoppingCar();
            car.setIsDelete(1);

            //清空购物车
            int carRow = carMapper.update(car, new QueryWrapper<ShoppingCar>().eq("userId", user.getId()));

            //判断购物车是否清空
            if (carRow > 0) {

                //订单类
                EasybuyOrder order1 = new EasybuyOrder();
                order1.setUserId(user.getId());  //赋值用户id
                order1.setLoginName(user.getLoginName());//赋值登陆名
                order1.setUserAddress(easybuyUserAddress.getAddress());  //赋值地址
                order1.setCost((float) sumPrice);  //赋值总价格
                order1.setSerialNumber(replaceUUID);  //赋值订单号
                order1.setCreateTime(new Date());
                order1.setStatus(1);   //赋值订单是否确认

                //添加订单
                int orderRow = orderMapper.insert(order1);

                //订单id
                int orderId = order1.getId();

                System.out.println("订单id:" + orderId);

                //判断订单添加成功
                if (orderRow > 0) {


                    for (int i = 0; i < list.size(); i++) {

                        //创建订单详情类
                        EasybuyOrderDetail detail = new EasybuyOrderDetail();
                        detail.setOrderId(orderId);//赋值订单主键
                        detail.setProductId(list.get(i));
                        detail.setQuantity(order.get(i).getNumber());
                        detail.setCost(lists.get(i));

                        //添加订单详情类
                        int rowsDelail = detailMapper.insert(detail);

                        //判断订单详情
                        if (rowsDelail > 0) {


                            //查询订单号
                            EasybuyOrder easybuyOrder = orderMapper.selectById(orderId);

                            //赋值订单号
                            session.setAttribute("orderMark", easybuyOrder.getSerialNumber());
                            //赋值地址
                            session.setAttribute("address", easybuyOrder.getUserAddress());

                            map.put("status", 1);
                            map.put("message", "提交成功");
                        } else {
                            map.put("status", 0);
                            map.put("message", "订单第" + i + "此详情添加失败");
                        }

                    }

                } else {

                    map.put("status", 0);
                    map.put("message", "订单添加失败！");

                }

            } else {

                map.put("status", 0);
                map.put("message", "订单提交失败，购物车清空失败！");
            }
        }

        return map;
    }

    /**
     * 跳转页面
     *
     * @return
     */
    @RequestMapping("/skip")
    public String skip(Model model, HttpSession session) {

        model.addAllAttributes(classify(session));

        return "BuyCar_Three";
    }


    /**
     * 查询分类
     *
     * @return
     */
    public Map classify(HttpSession session) {
        //获取session
        EasybuyUser userSession = (EasybuyUser) session.getAttribute("userSession");

        List<EasybuyProductCategory> list = categoryMapper.selectList(new QueryWrapper<EasybuyProductCategory>().eq("type", 1));
        List<EasybuyProductCategory> list2 = categoryMapper.selectList(new QueryWrapper<EasybuyProductCategory>().inSql("parentId", "select id from easybuy_product_category where type=1"));
        List<EasybuyProductCategory> list3 = categoryMapper.selectList(new QueryWrapper<EasybuyProductCategory>().inSql("parentId", "select id from easybuy_product_category where type=2"));
        List<EasybuyNews> easybuyNews = newsMapper.selectList(new QueryWrapper<EasybuyNews>().last("limit 0,5"));

        List<ShoppingCar> order = carMapper.selectList(new QueryWrapper<ShoppingCar>().eq("userId", userSession == null ? 0 : userSession.getId()).eq("isDelete", 0));    //查询订单

        //创建map集合
        Map<String, Object> map = new HashMap<>();

        map.put("list", list);//分类1
        map.put("list2", list2);//分类2
        map.put("list3", list3);//分类3
        map.put("easybuyNews", easybuyNews);  //新闻
        map.put("order", order);  //购物车

        //保留2为小数点
        DecimalFormat df = new DecimalFormat(".00");

        //总价格
        double sumPrice = 0;

        //循环订单
        for (ShoppingCar news : order) {

            //累加
            sumPrice += news.getSumPrice();
        }

        //保留2位小数点
        sumPrice = Double.parseDouble(df.format(sumPrice));

        //赋值总价格
        map.put("sumPrice", sumPrice);

        //赋值购物车数量
        session.setAttribute("order", order);

        //赋值总价格
        session.setAttribute("sumPrice", sumPrice);


        return map;
    }


}

